Your First AI application¶

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

No description has been provided for this image

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources¶

In [156]:
# TODO: Make all necessary imports.
import json
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from PIL import Image
import torch
from torch import nn, optim
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms, models
import torchvision.models as models
import tensorflow as tf
import os
import pathlib
import tensorflow_datasets as tfds

Load the Dataset¶

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [159]:
# TODO: Load the dataset with TensorFlow Datasets.
dataset, info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)
# TODO: Create a training set, a validation set and a test set.
train_ds = dataset['train']
val_ds = dataset['validation']
test_ds = dataset['test']
print(info)
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly
    occurring in the United Kingdom. Each class consists of between 40 and 258
    images. The images have large scale, pose and light variations. In addition,
    there are categories that have large variations within the category and several
    very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set. The
    training set and validation set each consist of 10 images per class (totalling
    1020 images each). The test set consists of the remaining 6149 images (minimum
    20 per class).
    
    Note: The dataset by default comes with a test size larger than the train size.
    For more info see this
    [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_dir='/Users/manarabdullah/tensorflow_datasets/oxford_flowers102/2.1.1',
    file_format=tfrecord,
    download_size=Unknown size,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=string),
        'image': Image(shape=(None, None, 3), dtype=uint8),
        'label': ClassLabel(shape=(), dtype=int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)

Explore the Dataset¶

In [162]:
# TODO: Get the number of examples in each set from the dataset info.
num_train_examples = info.splits['train'].num_examples
num_val_examples = info.splits['validation'].num_examples
num_test_examples = info.splits['test'].num_examples

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = info.features['label'].num_classes

#Print
print(f'The number of training examples include the following: {num_train_examples}\nThe number of validation examples include the following: {num_val_examples}\nThe number of of test examples include the following {num_test_examples}\nThe number of classes include the following: {num_classes}')
The number of training examples include the following: 1020
The number of validation examples include the following: 1020
The number of of test examples include the following 6149
The number of classes include the following: 102
In [164]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in train_ds.take(3):
    print("Image shape:", image.shape, "Label:", label.numpy())
    plt.figure()
    plt.imshow(image.numpy())
    plt.title("Label: " + str(label.numpy()))
    plt.axis('off')
    plt.show()
Image shape: (500, 667, 3) Label: 72
No description has been provided for this image
Image shape: (500, 666, 3) Label: 84
No description has been provided for this image
Image shape: (670, 500, 3) Label: 70
No description has been provided for this image
In [166]:
# TODO: Plot 1 image from the training set. Set the title of the plot to the corresponding image label. 
class_names = info.features['label'].names
for image, label in train_ds.take(1):
    plt.figure(figsize=(6,6))
    plt.imshow(image.numpy())
    plt.title(class_names[label.numpy()])
    plt.axis('off')
    plt.show()
No description has been provided for this image

Label Mapping¶

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [169]:
with open('label_map.json', 'r') as f:
    label_map = json.load(f)
In [171]:
# TODO: Plot 1 image from the training set. Set the title of the plot to the corresponding class name.
for image, label in train_ds.take(1):
    class_name = label_map[str(label.numpy())]
    plt.figure(figsize=(6,6))
    plt.imshow(image.numpy())
    plt.title(class_name)
    plt.axis('off')
    plt.show()
No description has been provided for this image

Create Pipeline¶

In [174]:
# TODO: Create a pipeline for each set.

image_size = (224, 224)
batch_size = 32

def image_process(image, label):
    image = tf.image.resize(image, image_size)
    image = image / 255.0
    return image, label

dataset_name = "oxford_flowers102"
dataset, info = tfds.load(dataset_name, as_supervised=True, with_info=True)
train_set = dataset['train']
validation_set = dataset['validation']
test_set = dataset['test']

train_set_pipeline = train_set.map(image_process).shuffle(1000).batch(batch_size).prefetch(tf.data.AUTOTUNE)
validation_set_pipeline = validation_set.map(image_process).batch(batch_size).prefetch(tf.data.AUTOTUNE)
test_set_pipeline = test_set.map(image_process).batch(batch_size).prefetch(tf.data.AUTOTUNE)

for images, labels in train_set_pipeline.take(3):
    ima = images.numpy()
    lab = labels.numpy()
    print(f"Image shape: {ima[0].shape}, Data type: {ima[0].dtype}")
    plt.imshow(ima[0])
    plt.colorbar()
    plt.show()
    print(f"Image Label: {lab[0]}")
Image shape: (224, 224, 3), Data type: float32
No description has been provided for this image
Image Label: 78
Image shape: (224, 224, 3), Data type: float32
No description has been provided for this image
Image Label: 19
Image shape: (224, 224, 3), Data type: float32
No description has been provided for this image
Image Label: 75

Build and Train the Classifier¶

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [265]:
# TODO: Build and train your network.
import tensorflow as tf
import tensorflow_hub as hub

IMAGE_SHAPE = (224, 224, 3)
NUM_CLASSES = 102
epochs = 10

inputs = tf.keras.Input(shape=IMAGE_SHAPE)
x = tf.keras.layers.Resizing(224, 224)(inputs)
x = tf.keras.layers.Lambda(lambda img: tf.cast(img, tf.float32), output_shape=(224, 224, 3))(x)
mobilenet_layer = hub.KerasLayer("https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/4", trainable=False, dtype=tf.float32)
x = tf.keras.layers.Lambda(lambda img: mobilenet_layer(img), output_shape=(1280,))(x)
x = tf.keras.layers.Dense(256, activation='relu')(x)
x = tf.keras.layers.Dropout(0.5)(x)
outputs = tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')(x)
model = tf.keras.Model(inputs, outputs)

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(train_pipeline, validation_data=val_pipeline, epochs=epochs)
Epoch 1/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 11s 272ms/step - accuracy: 0.0280 - loss: 4.7811 - val_accuracy: 0.2176 - val_loss: 4.0243
Epoch 2/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 242ms/step - accuracy: 0.1990 - loss: 3.6876 - val_accuracy: 0.4324 - val_loss: 2.9336
Epoch 3/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 232ms/step - accuracy: 0.3775 - loss: 2.7255 - val_accuracy: 0.6059 - val_loss: 2.1079
Epoch 4/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 235ms/step - accuracy: 0.5613 - loss: 1.9271 - val_accuracy: 0.6559 - val_loss: 1.6451
Epoch 5/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 249ms/step - accuracy: 0.6855 - loss: 1.3364 - val_accuracy: 0.7137 - val_loss: 1.3563
Epoch 6/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 238ms/step - accuracy: 0.7620 - loss: 1.0046 - val_accuracy: 0.7314 - val_loss: 1.2042
Epoch 7/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 238ms/step - accuracy: 0.8180 - loss: 0.7973 - val_accuracy: 0.7569 - val_loss: 1.0679
Epoch 8/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 239ms/step - accuracy: 0.8659 - loss: 0.6199 - val_accuracy: 0.7686 - val_loss: 0.9945
Epoch 9/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 241ms/step - accuracy: 0.9014 - loss: 0.4988 - val_accuracy: 0.7775 - val_loss: 0.9317
Epoch 10/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 8s 238ms/step - accuracy: 0.9036 - loss: 0.4474 - val_accuracy: 0.7784 - val_loss: 0.8916

Testing your Network¶

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [180]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss', fontsize = 10, weight = 'bold')
plt.xlabel('Epoch', fontsize = 10, weight = 'semibold')
plt.ylabel('Loss', fontsize = 10, weight = 'semibold')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy', fontsize = 10, weight = 'bold')
plt.xlabel('Epoch', fontsize = 10, weight = 'semibold')
plt.ylabel('Accuracy', fontsize = 10, weight = 'semibold')
plt.legend()
plt.show()

# TODO: Print the loss and accuracy values achieved on the entire test set.

test_loss, test_accuracy = model.evaluate(test_pipeline)
print("Test Loss:", test_loss)
print("Test Accuracy:", test_accuracy)
No description has been provided for this image
193/193 ━━━━━━━━━━━━━━━━━━━━ 21s 110ms/step - accuracy: 0.7524 - loss: 1.0163
Test Loss: 1.0100749731063843
Test Accuracy: 0.7586599588394165

Save the Model¶

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [182]:
# TODO: Save your trained model as a Keras model.
model.save("flower_classifier.h5")
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`. 

Load the Keras Model¶

Load the Keras model you saved above.

In [211]:
# TODO: Load the Keras model
import tensorflow as tf
from tensorflow.keras.models import load_model

# Load model without compiling to avoid errors
try:
    model = load_model("/Users/manarabdullah/Documents/GitHub Cloned Repos/ML - Image Classifier Project/Data/flower_classifier.h5", compile=False)
    print("Model loaded successfully!")
except Exception as e:
    print("Error loading model:", str(e))
    model = None


if model:
    model.summary()
Model loaded successfully!
Model: "functional_2"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ input_layer_11 (InputLayer)     │ (None, 224, 224, 3)    │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ resizing_11 (Resizing)          │ (None, 224, 224, 3)    │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ lambda_12 (Lambda)              │ (None, 224, 224, 3)    │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ lambda_13 (Lambda)              │ (None, 1280)           │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_4 (Dense)                 │ (None, 256)            │       327,936 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dropout_2 (Dropout)             │ (None, 256)            │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_5 (Dense)                 │ (None, 102)            │        26,214 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
 Total params: 354,150 (1.35 MB)
 Trainable params: 354,150 (1.35 MB)
 Non-trainable params: 0 (0.00 B)

Inference for Classification¶

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing¶

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [275]:
# TODO: Create the process_image function

import tensorflow as tf
import numpy as np
from PIL import Image

def process_image(img_input):
    if isinstance(img_input, str):
        img = Image.open(img_input)
        img = np.array(img)
    else:
        img = img_input
    img_tensor = tf.convert_to_tensor(img, dtype=tf.float32)
    img_tensor = tf.image.resize(img_tensor, (224, 224))
    img_tensor = img_tensor / 255.0
    img_tensor = np.expand_dims(img_tensor, axis=0)
    return img_tensor

def predict(image_path, model, top_k=5):
    processed_img = process_image(image_path)
    predictions = model.predict(processed_img)[0]
    top_indices = np.argsort(predictions)[-top_k:][::-1]
    top_probs = predictions[top_indices]
    top_classes = [str(i) for i in top_indices]
    return top_probs, top_classes

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [192]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
No description has been provided for this image

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference¶

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [273]:
# TODO: Create the predict function
image_path = "./hard-leaved_pocket_orchid.jpg"
probs, classes = predict(image_path, model, top_k=5)
print(f'The predicted classes include: {classes}')
print(f'The predicted probabilities include: {probs}')
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 35ms/step
The predicted classes include: ['1', '5', '67', '12', '96']
The predicted probabilities include: [9.9698347e-01 8.0754003e-04 4.9684860e-04 2.9588363e-04 2.6195668e-04]

Sanity Check¶

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

No description has been provided for this image

You can convert from the class integer labels to actual flower names using class_names.

In [271]:
# TODO: Plot the input image along with the top 5 classes
test_images = [
    './cautleya_spicata.jpg',
    './hard-leaved_pocket_orchid.jpg',
    './orange_dahlia.jpg',
    './wild_pansy.jpg'
]

for image_path in test_images:
    probs, class_names = predict(image_path, model, top_k=5)
    
    print(probs)
    print(class_names)
    
    fig, (ax1, ax2) = plt.subplots(figsize=(12,6), ncols=2)
    
    img = Image.open(image_path).resize((224, 224))
    ax1.imshow(img)
    ax1.set_title(f"Input Image: {os.path.basename(image_path)}")
    ax1.axis('off')
    
    ax2.barh(class_names, probs, color='skyblue')
    ax2.set_title(f"Top 5 Predictions for {os.path.basename(image_path)}")
    ax2.set_xlabel('Probability')
    ax2.set_ylabel('Class Name')
    ax2.set_xlim(0, 1)
    
    plt.tight_layout()
    plt.show()
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 41ms/step
[0.95890903 0.01690474 0.00517131 0.00388848 0.00365079]
['60', '23', '38', '36', '45']
No description has been provided for this image
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 25ms/step
[9.9698347e-01 8.0754003e-04 4.9684860e-04 2.9588363e-04 2.6195668e-04]
['1', '5', '67', '12', '96']
No description has been provided for this image
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 37ms/step
[0.25348118 0.2427889  0.09461075 0.07725585 0.07385448]
['58', '4', '40', '70', '65']
No description has been provided for this image
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 29ms/step
[0.9836556  0.0033812  0.00147167 0.0014386  0.00129942]
['51', '33', '65', '83', '64']
No description has been provided for this image
In [277]:
import os

os.system('jupyter nbconvert --to html Project_Image_Classifier_Project.ipynb')
[NbConvertApp] Converting notebook Project_Image_Classifier_Project.ipynb to html
[NbConvertApp] WARNING | Alternative text is missing on 16 image(s).
[NbConvertApp] Writing 5034210 bytes to Project_Image_Classifier_Project.html
Out[277]:
0
In [ ]: